package com.ma.chapter4.t2;

import lombok.extern.slf4j.Slf4j;

import static com.ma.util.Sleeper.sleep;

/**
 * @ClassName Test1
 * @Author: mayongqiang
 * @DATE 2022/3/4 20:23
 * @Description: 两阶段终止模式
 */

/**
 * 两阶段终止模式  例：后台监控程序
 */
@Slf4j(topic = "m.Test1")
public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination tpt = new TwoPhaseTermination();
        tpt.start();
        Thread.sleep(3500);
        tpt.stop();
    }
}

@Slf4j(topic = "m.TwoPhaseTermination")
class TwoPhaseTermination {
    private Thread monitor;

    //启动监控线程
    public void start() {
        monitor = new Thread(() -> {
            while (true) {
                Thread current = Thread.currentThread();
                if (current.isInterrupted()) {
                    log.debug("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000); //情况1
                    log.debug("执行监控记录"); //情况2
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //重新设置打断标志
                    current.interrupt();
                }

            }
        }, "monitor");
        monitor.start();

    }

    //停止监控线程
    public void stop() {
        monitor.interrupt();
    }
}










